<?php

    namespace yaliSDK\live;

    use think\Exception;
    use yaliSDK\common\BaseRepository;
    use yaliSDK\common\Constrants;
    use yaliSDK\common\IRepository;

    class LiveRepository extends BaseRepository implements IRepository {
        private static $TABLE = 'live';

        function save($data, $option = []): bool {


            if ($this->db->name(self::$TABLE)->insert($data) > 0) {
                $liveId = $this->db->name(self::$TABLE)->getLastInsID();
                if ($option['products']) {
                    foreach ($option['products'] as $product) {
                        $this->db->name('live_product')->insert(['live_id' => $liveId, 'product_id' => $product['id']]);
                    }

                }
                return true;
            }
            return false;
        }

        function get($id, $option = []) {
            $result = null;
            try {
                $result = $this->db->name(self::$TABLE)->where(['id' => $id])->find();
                // 携带产品列表
                if (!empty($option['products'])) {
                    $products = $this->db->name('live_product')->where(['live_id' => $id])->select();
                    if ($result && $products) {
                        $result['products'] = $products;
                    }
                }
            } catch (Exception $e) {

            }
            return $result;
        }

        function createOrderRule($web_id, $uid) {

        }

        function lists($option = []) {
            $result = null;
            try {
                 $cb = function () use ($option) {
                    $keywords = $option['keywords'] ?? '';
                    $uid = $option['uid'] ?? null;// 访问用户uid
                    $id = $option['id'] ?? null;
                    $status = $option['status'] ?? null;
                    $anchorId = $option['anchorId'] ?? null;// 主播id
                    $productId = $option['productId'] ?? null;// 产品id
                    $isShop = $option['isShop'] ?? true;// 产品id
                    $domain = $option['domain'] ?? null;// 域名
                    $orderType = $option['orderType'] ?? null;
                    $liveing = $option['liveing'] ?? null; //判断状态status =1 （liveing=1	&current_id!null正在直播/liveing=2	current_id=null正在进行）
                     $web_id =$option['web_id']??null;//判断当前站点
//                    $orderType = 2;
                    $query = $this->db
                        ->name(self::$TABLE)
                        ->alias('l');
                    if ($isShop) {

                        $query->join('yali_multishop_info s', 's.web_id = l.web_id and s.uid=l.uid')->field('s.shop_name, s.shop_logo, s.feedback as shop_feedback');
                    }
                    if (!empty($keywords)) {
                        $query->join('yali_anchor a', 'a.id = l.anchor_id')->where("a.name  like '%$keywords%' or  l.title like '%$keywords%'  or s.shop_name like '%$keywords%'  ");
//                            ->where([
//                                'a.name' => ['like', '%' . $keywords . '%'],
//                            ])->whereOr(['l.title' => ['like', '%' . $keywords . '%']]);
                    }
                    $cb = function ($status) {
                        return $status === Constrants::$LIVE_DEL || $status === Constrants::$LIVE_WAIT || $status === Constrants::$LIVE_START || $status === Constrants::$LIVE_END;
                    };
                    
                     if($status==1&&$liveing==1){
                         $query->where(['l.current_id' => ['eq', '']]);
                     }else  if($status==1&&$liveing==2){
                         $query->where(['l.current_id' => ['neq', '']]);
                     }
                     if(!empty($web_id)){
                         $query->where(['l.web_id' =>$web_id]);
                     }

                    $status = str_replace(' ', '', $status);
                    if ($status !== '' && !is_null($status)) {
                        $s = explode(',', $status);

                        if (!empty($s)) {
                            $args = [];
                            foreach ($s as $index => $a) {
                                $status = trim($a);

                                $status = intval($status);
                                if ($cb($status)) {
                                    array_push($args, $status);
                                }
                            }

                            $query->where(['l.status' => ['in', $args]]);
                        } else {
                            $query->where(['l.status' => ['in', [Constrants::$LIVE_WAIT, Constrants::$LIVE_START, Constrants::$LIVE_END]]]);
                        }
                    } else {
                        $query->where(['l.status' => ['in', [Constrants::$LIVE_WAIT, Constrants::$LIVE_START, Constrants::$LIVE_END]]]);
                    }
                    if ($id) {
                        $query->where(['l.id' => $id]);
                    }
                    // 获取统计人数
                   $query->join('live_visitor z', 'z.live_id = l.id', 'left')->field('count(z.id) as total_visitor')->group('l.id');
                    if ($anchorId) {
                        $query->where(['l.anchor_id' => $anchorId]);
                    }
                    if ($productId) {
                        $query->join('yali_live_product o', 'o.live_id=l.id');
                        $query->where(['o.product_id' => $productId]);
                    }
                    $web_id = $this->getWebIdByDomain($domain);
                    if ($web_id) {

                        $query->where(['l.web_id' => $web_id]);
                    }

                    // 优先直播，未开始，结束
                    $o_status = 'case when l.status=1 then 2 when l.status=0 then 1 ELSE -1 end desc, l.addtime desc';
                    if ($orderType === 1) {// 最热, 规则：必须是正在进行中的活动，有房间号的优先派前
                        $o_status = 'case when l.current_room is not null then 2 ELSE -1 end desc, l.addtime desc';
                        $query->where(['l.status'=>Constrants::$LIVE_START])->orderRaw($o_status);

                    } else if ($orderType === 2) {// 关注主播
                        $query->join('live_follow f', 'f.anchor_id=l.anchor_id and f.web_id=l.web_id')->where(['f.uid' => $uid]);
                        $query->orderRaw($o_status);

                    } else if ($orderType === 3) {// 最新，时间降序
                        $query->orderRaw($o_status);
                        
                    } elseif ($orderType === 4 ) {
                        $o_status = 'case when l.current_room is not null then 2 ELSE -1 end desc, l.addtime desc';
                        $query->orderRaw($o_status);
                    }
                    $query->field('l.*');
                    return $query;
                };

                $total = $cb()->count();// 当前总数

                $isCount = $option['isCount'] ?? false;
                if (empty($isCount)) {
                    $page = $option['page'] ?? 1;
                    $limit = $option['rows'] ?? 20;
                    $result = $cb()->page($page, $limit)->select();
                    if($result!==false){  //转换统计数为w
                        foreach ((array)$result as $k=>$v ){
                            $result[$k]['total_visitor']=$v['total_visitor'];
                            $result[$k]['point_praise']=$v['point_praise'];
                            $result[$k]['total_people']=$v['total_people'];
                        }
                    }
                }

                if (!empty($result) && !empty($result[0]) && empty($result[0]['id'])) {
                    $result = [];
                }
                return [
                    'list' => $result,
                    'total' => $total,
                ];
            } catch (Exception $e) {
                print_r($e->getMessage());
                die;
            }

        }

        function update($data, $option = []) {
            try {
                $d = $this->db->name(self::$TABLE)->update($data);
                $liveId = $data['id'];
                if (!empty($option['products'])) {
                    $this->db->name('live_product')->where(['live_id' => $liveId])->delete();
                    foreach ($option['products'] as $product) {
                        $this->db->name('live_product')->insert(['live_id' => $liveId, 'product_id' => $product['id']]);
                    }

                }
                return $d !== false;
            } catch (Exception $e) {
                print_r($e->getMessage());
                die;
            }
            return false;
        }

        // 当前直播产品
        function currentLiveProduct($liveId, $productId) {
            try {
                $d = $this->db->name(self::$TABLE)->where(['id' => $liveId])->update(['current_product' => $productId]);
                return $d !== false;
            } catch (Exception $e) {
                print_r($e->getMessage());
                die;
            }

        }

        // 更新产品价格
        function updateProductPrice($liveId, $productId, $unitPrice) {
            try {
                $live = $this->db->name(self::$TABLE)->where(['id' => $liveId])->field('is_change_price')->find();
                if (!empty($live) && !empty($live['is_change_price']) && $productId && !empty($unitPrice)) {
                    $d = $this->db->name('product')->where(['id' => $productId])->update(['unit_price' => $unitPrice*100]);
                    return $d !== false;
                }
                return false;
            } catch (Exception $e) {
                print_r($e->getMessage());
                die;
            }
        }

        // 产品列表
        function productList($liveId, int $rows = 10) {
            $list = null;
            try {
                $cb = function () use ($liveId) {
                    return $this->db
                        ->name('product')->alias('p')
                        ->join('yali_live_product o', 'o.product_id=p.id')
                        ->join('product_content c', 'c.product_id=p.id')
                        ->where(['o.live_id' => $liveId])->field('p.id,round(p.unit_price/100, 2) as unit_price, c.title, c.pic, c.set_id,o.order_id')->order('o.order_id asc');

                };
                $total = $cb()->count();
                $list = $cb()->page(1, $rows)->select();
                /*if (is_array($list)) {
                    $list = array_map(function($i) {
                        if (!empty($i['pic'])) {
                            $i['pic'] = 'http://oixavq5ec.bkt.clouddn.com/'.$i['pic'];
                        }
                        return $i;
                    }, $list);
                }*/
                return [
                    'total' => $total,
                    'list' => $list,
                ];
            } catch (Exception $e) {
                print_r($e->getMessage());
                die;
            }
        }

        // 获取活动所属的店铺
        function shops($option = []) {
            try {
                $anchorId = $option['anchorId'] ?? null;
                $query = $this->db
                    ->name('multishop_info')
                    ->alias(' s')
                    ->join('yali_live l', 's.uid=l.uid and s.web_id=l.web_id')
                    ->field('s.uid, s.shop_name,s.web_id')
                    ->group('s.web_id');
                if (!empty($anchorId)) {
                    $query->where(['l.anchor_id' => $anchorId]);

                }
                $result = $query->select();
                return $result;
            } catch (Exception $e) {
                print_r($e->getMessage());
                die;
            }

        }

        function isExist($id, $option): bool {
            $key = $option['key'] ?? 'id';
            return $this->db->name(self::$TABLE)->where([$key => $id])->count('id') > 0;
        }
    }